/* ANCHOR: all */
// Rust sokoban
// main.rs

use ggez::{conf, event, Context, GameResult};
use hecs::World;

use std::path;

mod components;
mod constants;
mod entities;
mod events;
mod map;
mod systems;


use crate::components::{GameplayState};  // 添加ResourceManager和GameStyle


// ANCHOR: game
// This struct will hold all our game state
// For now there is nothing to be held, but we'll add
// things shortly.
struct Game {
    world: World,
    main_menu: systems::menu::MainMenuState,
    level_select: systems::menu::LevelSelectState,
    difficulty_select: systems::menu::DifficultySelectState,
}
// ANCHOR_END: game

//这部分做了修改
impl event::EventHandler<ggez::GameError> for Game {
    fn update(&mut self, context: &mut Context) -> GameResult {
        
        let current_state = {
            let mut query = self.world.query::<&mut crate::components::Gameplay>();
            let gameplay = query.iter().next().unwrap().1;
            gameplay.state // 复制状态值
        }; // query 在这里被释放
        
        match current_state {
            GameplayState::MainMenu => {
                // 删除这行：systems::rendering::run_menu_rendering(&self.world, context, self.main_menu.selected);
                // 只处理菜单逻辑
                systems::menu::run_menu_system(&mut self.world, context, &mut self.main_menu);
            }
            GameplayState::LevelSelect => {
                systems::menu::run_level_select_system(&mut self.world, context, &mut self.level_select, &mut self.difficulty_select);
            }
            GameplayState::Playing => {
                // Run input system
                {
                    systems::input::run_input(&mut self.world, context);
                }
            
                // Run gameplay state
                {
                    systems::gameplay::run_gameplay_state(&self.world, context);
                }
            
                // Run events processing
                {
                    systems::events::run_process_events(&mut self.world, context);
                }
            }
            GameplayState::Won => {
                // Run win menu system
                systems::menu::run_win_menu_system(&mut self.world, context);
            }
            GameplayState::Return => {  // 新增
                systems::menu::run_return_menu_system(&mut self.world, context);
            }

            GameplayState::Failed => {
                // Run failed menu system
                systems::menu::run_failed_menu_system(&mut self.world, context);
            }
            GameplayState::DifficultySelect => {
                // 难度选择系统
                systems::menu::run_difficulty_select_system(&mut self.world, context, &mut self.difficulty_select);
            }
            
        }

        // Get and update time resource
        {
            let mut query = self.world.query::<&mut crate::components::Time>();
            let time = query.iter().next().unwrap().1;
            time.delta += context.time.delta();
        }

        Ok(())
    }

    fn draw(&mut self, context: &mut Context) -> GameResult {
        let current_state = {
            let mut query = self.world.query::<&crate::components::Gameplay>();
            let gameplay = query.iter().next().unwrap().1;
            gameplay.state
        };
            
        match current_state {
            GameplayState::Playing => {
                // 只在游戏进行时渲染游戏实体
                systems::rendering::run_rendering(&self.world, context);
            }
            GameplayState::MainMenu => {
                systems::rendering::run_menu_rendering(&self.world, context, self.main_menu.selected);
            }
            GameplayState::LevelSelect => {
                systems::rendering::run_level_select_rendering(&self.world, context, self.level_select.selected);
            }
            GameplayState::Won => {
                systems::rendering::run_win_menu_rendering(&self.world, context);
            }
            GameplayState::Return => {
                systems::rendering::run_return_menu_rendering(&self.world, context);
            }
            GameplayState::Failed => {
                systems::rendering::run_failed_menu_rendering(&self.world, context);
            }
            GameplayState::DifficultySelect => {
                systems::rendering::run_difficulty_select_rendering(&self.world, context, self.difficulty_select.selected);
            }
            _ => {
                // 默认渲染游戏实体
                systems::rendering::run_rendering(&self.world, context);
            }
        }
    
        Ok(())
    }
}
// ANCHOR_END: handler

// ANCHOR: main
pub fn main() -> GameResult {
    let mut world = World::new();

    // Create a game context and event loop
    let context_builder = ggez::ContextBuilder::new("rust_sokoban", "sokoban")
        .window_setup(conf::WindowSetup::default().title("Rust Sokoban!"))
        .window_mode(conf::WindowMode::default().dimensions(800.0, 600.0))  // 使用动态路径
        .add_resource_path(path::PathBuf::from("./resources")); 

    let (mut context, event_loop) = context_builder.build()?;

    entities::create_gameplay(&mut world);
    entities::create_time(&mut world);
    entities::create_event_queue(&mut world);
    entities::create_audio_store(&mut world);

    // Create the game state
    let game = Game { 
        world, 
        main_menu: systems::menu::MainMenuState::default(),
        level_select: systems::menu::LevelSelectState::default(),
        difficulty_select: systems::menu::DifficultySelectState::default(),
        // 删除 style_select: systems::menu::StyleSelectState::default(),
    };
    
    event::run(context, event_loop, game)
}
// ANCHOR_END: main

/* ANCHOR_END: all */